package com.ctgu.chatapp.view.DialogFragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import com.ctgu.chatapp.Service.RequestService
import com.ctgu.chatapp.databinding.DialogAddfriendBinding
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.model.Retrofit.IMSServiceImpl
import com.ctgu.chatapp.model.pojo.Request
import com.ctgu.chatapp.view.IMSApplication
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.async
import kotlinx.coroutines.launch


class AddFriend(val chatID: Long, val friendID: Long) : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val dataBase = DataBaseManager.getInstance(IMSApplication.context)
        val binding = DialogAddfriendBinding.inflate(inflater, container, false)
        binding.addinfoSent.setOnClickListener {
            if (binding.addinfoGroup.text.toString().isNotEmpty()) {
                CoroutineScope(IO).launch {
                    RequestService.sendFriendRequest(
                        chatID,
                        friendID,
                        binding.addinfoGroup.text.toString()
                    )
                    /**
                     * 选择加对方为好友,添加一条请求消息到数据库中
                     * */
                    async {
                        val result = IMSServiceImpl.imsServiceImpl.service.getInformation(friendID)
                        dataBase.getInformationDao()
                            .addInformation(result)
                    }
                    async {
                        dataBase.getRequestDao()
                            .addFriendRequest(
                                Request(
                                    chatID,
                                    friendID,
                                    0,
                                    System.currentTimeMillis()
                                )
                            )
                    }
                }
            }
            this.onDismiss(requireDialog())
        }
        binding.addinfoCancel.setOnClickListener {
            this.onDismiss(requireDialog())
        }
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        val params = dialog!!.window!!.attributes
        params.width = 350
        dialog!!.window!!.attributes = params as WindowManager.LayoutParams
    }
}